package com.ruihang.generalibrary.ui.adapter;

import android.content.Context;
import android.widget.BaseAdapter;

import com.ruihang.generalibrary.ui.util.IAutoLoadMore;

import java.util.List;

/**
 * Created by panxd on 2016/9/7.
 */
public abstract class BaseAbstractAdapter<T> extends BaseAdapter {
    protected Context context;

    protected List<T> datas;

    protected IAutoLoadMore<T> loadMoreListener;

    protected boolean hasMore=true;//是否还有更多数据
    //加载的更多的界限
    protected int loadLimitLess=3;//数据较少时使用，倒数第loadLimitLess条加载更多
    protected int loadLimitMore=6;//数据较多时使用，loadLimitMore

    protected int moreOrLessLimit=8;//数据为较多或较少的标准，大于此数使用较多的界限，否则使用较少的界限

    protected boolean isLoadingMore;//是否正在加载更多

    public BaseAbstractAdapter(Context context, List<T> datas) {
        this.context = context;
        this.datas = datas;
    }

    public BaseAbstractAdapter(Context context) {
        this.context = context;
    }
    @Override
    public int getCount() {
        if(datas!=null){
            return datas.size();
        }
        return 0;
    }

    @Override
    public T getItem(int i) {
        return datas.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    public void setDatas(List<T> list){
        this.datas=list;
        notifyDataSetChanged();
    }

    protected void callLoad(int pos){

        if(hasMore && !isLoadingMore && loadMoreListener !=null ) {
            int limit = datas.size() > moreOrLessLimit ? loadLimitMore : loadLimitLess;
            if (pos >= datas.size() - limit - 1) {//倒数第limit条时加载更多
//                isLoadingMore=loadMoreListener.OnAutoLoadMore(this, datas);
            }
        }
    }

    public void addDatas(List<T> list){
        if(list==null || list.size()==0){
            return;
        }
        if(this.datas==null){
            setDatas(list);
        }else{
            this.datas.addAll(list);
            notifyDataSetChanged();
        }
    }

    public void clean(){
        if(datas!=null){
            datas.clear();
            notifyDataSetChanged();
        }
    }

    public void replaceData(int pos,T t){
        if(pos<0 || pos>=getCount() || t==null){
            return;
        }
        datas.remove(pos);
        datas.add(pos,t);
        notifyDataSetChanged();
    }

    public BaseAbstractAdapter setLoadMoreListener(IAutoLoadMore<T> loadMoreListener) {
        this.loadMoreListener = loadMoreListener;
        return this;
    }

    public BaseAbstractAdapter setLoadingMore(boolean loadingMore) {
        isLoadingMore = loadingMore;
        return this;
    }

    public boolean isLoadingMore() {
        return isLoadingMore;
    }

    //    public void loadComplete

    public void setHasMore(boolean hasMore) {
        this.hasMore = hasMore;
    }
}
